package cn.lg.soar.cloud.core.config;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.IpUtil;
import cn.lg.soar.core.handler.ex.ErrorResult;
import cn.lg.soar.core.handler.ex.SoarExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局拦截异常处理异常
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Slf4j(topic = "CloudExceptionHandler")
@RestControllerAdvice
public class CloudExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public HttpResult<?> handle(Exception e, HttpServletRequest request, HttpServletResponse response) {
        ErrorResult result = SoarExceptionHandler.handle(e, msg -> {
            log.warn("{} >>> {} >>> {}",
                    IpUtil.getRemoteIp(request),
                    request.getServletPath(),
                    msg
            );
        });
        response.setStatus(result.getStatus());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return result.getResult();
    }

    public static void init() {}
}
